const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV, // 使用当前环境
});

const db = cloud.database();
const _ = db.command;

// 领取优惠券包的主要逻辑
async function claimCoupon(request) {
  const { couponPackageId, openId, testCase } = request;
  
  const wxContext = cloud.getWXContext();
  const openIdOrMockOpenId = openId || wxContext.OPENID; // 获取用户的 openId

  try {
    // 查询指定的优惠券包
    const couponPackageRes = await db
      .collection("coupon_config")
      .where({
        coupon_package_id: couponPackageId,
      })
      .get();

    if (couponPackageRes.data.length === 0) {
      console.error("Coupon package not found", couponPackageId);
      return {
        code: 404,
        message: "Coupon package not found",
      };
    }

    // 按版本号降序排序，获取最新版本
    couponPackageRes.data.sort((p1, p2) => p2.coupon_package_version - p1.coupon_package_version);
    const latestCouponPackage = couponPackageRes.data[0];

    // 检查用户是否已经领取过该优惠券包
    const couponPackageHasClaimedRes = await db.collection("coupon_record")
      .where({
        out_user_id: openIdOrMockOpenId,
        coupon_package_id: latestCouponPackage.coupon_package_id,
        coupon_package_version: latestCouponPackage.coupon_package_version
      }).get();

    if (couponPackageHasClaimedRes.data.length > 0) {
      return {
        code: 200,
        message: "已经领取过了啦",
      };
    }

    const currentTs = new Date(); // 当前时间戳

    // 构造批量插入的优惠券记录
    const couponRecords = latestCouponPackage.coupon_items.map((item) => ({
      out_user_id: openIdOrMockOpenId,
      coupon_package_id: couponPackageId,
      coupon_package_version: latestCouponPackage.coupon_package_version,
      expiration_days: item.expiration_days,
      coupon_id: item.coupon_id,
      coupon_desc: item.coupon_desc,
      type: item.type,
      price: item.price,
      tips: item.tips,
      quantity: item.quantity,
      claim_time: currentTs,
      create_ts: currentTs,
      update_ts: currentTs
    }));

    // 插入到 coupon_record 表中
    const insertRes = await db.collection("coupon_record").add({
      data: couponRecords,
    });

    return {
      code: 200,
      message: "Coupon package claimed successfully",
      data: {
        insertedCount: insertRes._ids.length, // 返回插入成功的记录数
      },
    };

  } catch (error) {
    console.error("Error claiming coupon package:", error);
    return {
      code: 500,
      message: "Error claiming coupon package",
      error: error.message,
    };
  }
}

// 格式化日期为 YYYY-MM-DD HH:MM:SS 格式
function formatDateToYY_MM_DD_HH_MM_SS(date) {
  try {
    // 确保 date 是有效的 Date 对象
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      return "无效时间"; // 如果时间无效，返回默认字符串
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error("Error formatting date:", error);
    return "时间格式错误"; // 返回默认错误字符串
  }
}

// 将日期转换为 YYYY年MM月DD日 格式（北京时间）
function formatDateToChineseBeijing(date) {
  try {
    // 确保 date 是有效的 Date 对象
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      return "无效时间";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    return `${year}年${month}月${day}日`;
  } catch (error) {
    console.error("Error formatting Beijing date:", error);
    return "时间格式错误";
  }
}

// 根据状态过滤并计算优惠券数量
function buildCouponByStatus(couponDocs, status) {
  let coupons = [];
  const currentTime = new Date(); // 当前时间

  if (status === "toUse") {
    // 筛选待使用的优惠券（quantity > used_quantity 或 used_quantity 未定义）
    coupons = couponDocs.filter(coupon => {
      const expirationTime = new Date(coupon.claim_time.getTime() + parseInt(coupon.expiration_days, 10) * 24 * 60 * 60 * 1000); // 计算过期时间
      const usedQuantity = coupon.used_quantity || 0; // 如果 `used_quantity` 是 undefined，则默认值为 0
      return expirationTime > currentTime && coupon.quantity - usedQuantity > 0;
    });
  } else if (status === "used") {
    // 筛选已使用的优惠券（used_quantity > 0）
    coupons = couponDocs.filter(coupon => {
      const usedQuantity = coupon.used_quantity || 0; // 如果 `used_quantity` 是 undefined，则默认值为 0
      return usedQuantity > 0;
    });
  } else if (status === "expired") {
    // 筛选已过期的优惠券（claim_time + expiration_days 的失效时间 < 当前时间）
    coupons = couponDocs.filter(coupon => {
      const expirationDays = parseInt(coupon.expiration_days, 10); // 转换 expiration_days 为整数
      const expirationTime = new Date(coupon.claim_time.getTime() + expirationDays * 24 * 60 * 60 * 1000); // 计算过期时间
      const usedQuantity = coupon.used_quantity || 0; // 如果 `used_quantity` 是 undefined，则默认值为 0
      return expirationTime < currentTime && coupon.quantity - usedQuantity > 0; // 过期且剩余未使用数量 > 0
    });
  }

  return coupons;
}

// 获取用户优惠券列表
async function getCouponsByUserId(request) {
  const { openId, status, userId } = request;
  const wxContext = cloud.getWXContext();
  const openIdOrMock = openId || userId || wxContext.OPENID;

  try {
    // 从集合 coupon_record 中取前 100 条记录，按 create_ts 倒序排序
    const res = await db
      .collection("coupon_record")
      .where({
        out_user_id: openIdOrMock, // 使用 openId 作为筛选条件
      })
      .orderBy("create_ts", "desc")
      .limit(100)
      .get();

    const couponDocs = res.data || []; // 获取文档数据
    let coupons = buildCouponByStatus(couponDocs, status);

    // 转换为前端需要的字段格式
    const couponVos = coupons.map(coupon => {
      const usedQuantity = coupon.used_quantity || 0; // 如果 `used_quantity` 是 undefined，则默认值为 0
      const remainingQuantity = coupon.quantity - usedQuantity; // 剩余未使用的张数

      return {
        couponPackageId: coupon.coupon_package_id,
        couponPackageVersion: coupon.coupon_package_version,
        couponId: coupon.coupon_id,
        couponDesc: coupon.coupon_desc,
        type: coupon.type,
        price: coupon.price,
        expirationDays: coupon.expiration_days,
        tips: coupon.tips,
        quantity:
          status === "toUse" ? remainingQuantity : // 待使用状态：展示剩余未使用张数
          status === "used" ? usedQuantity : // 已使用状态：展示已使用张数
          status === "expired" ? remainingQuantity : // 过期状态：展示剩余未使用张数
          coupon.quantity, // 默认展示总张数
        expirationTime: formatDateToChineseBeijing(
          new Date(coupon.claim_time.getTime() + parseInt(coupon.expiration_days, 10) * 24 * 60 * 60 * 1000)
        ), // 计算过期时间并格式化
        claimTime: formatDateToYY_MM_DD_HH_MM_SS(coupon.claim_time), // 格式化领取时间
        createTime: formatDateToYY_MM_DD_HH_MM_SS(coupon.create_ts), // 格式化创建时间
        updateTime: formatDateToYY_MM_DD_HH_MM_SS(coupon.update_ts), // 格式化更新时间
      };
    });

    // 返回成功响应
    return {
      code: 200,
      message: "success",
      data: couponVos,
    };
  } catch (error) {
    console.error(error);
    // 返回错误响应
    return {
      code: 500,
      message: "Internal server error",
      data: [],
    };
  }
}

// 生成默认响应结构
function generateDefaultRes() {
  let res = {
    code: 200,
    message: "success",
    data: {
      "couponPackageId": "cp1",
      "hasClaimed": true,
      "couponItems": [{
          "couponId": "001",
          "tips": "无门槛",
          "price": "9.9"
        },
        {
          "couponId": "001",
          "tips": "无门槛",
          "price": "9.9"
        }
      ]
    },
  }
  res.data = null;
  return res;
}

// 从当前版本券包配置中筛选用户已领取的券
function couponsFromCurVersionPackageConfig(couponDocs, schoolCouponPackageConfigDoc) {
  // 解构出筛选条件
  const { coupon_package_id, coupon_package_version } = schoolCouponPackageConfigDoc;
  // 筛选 couponDocs，符合条件的返回
  return couponDocs.filter(couponDoc =>
      couponDoc.coupon_package_id === coupon_package_id &&
      couponDoc.coupon_package_version === coupon_package_version
  );
}

// 构建券包VO对象
function buildCouponPackageVo(schoolCouponPackageConfigDoc) {
  let res = {};
  let coponItemVos = [];
  schoolCouponPackageConfigDoc.coupon_items.forEach(
    item => {
      let itemVo = {};
      coponItemVos.push(itemVo);
      itemVo.couponId = item.coupon_id;
      itemVo.tips = item.tips;
      itemVo.price = item.price;
      if (item.quantity > 1) {
        for (let i = 0; i < item.quantity - 1; i++) {
          coponItemVos.push(itemVo);
        }
      }
    }
  );
  res.couponPackageId = schoolCouponPackageConfigDoc.coupon_package_id;
  res.couponItems = coponItemVos;
  return res;
}

// 按学校显示优惠券
async function showCouponsBySchool(request) {
  const { openId, schoolAddressCode } = request;
  const wxContext = cloud.getWXContext();
  const openId_ = openId || wxContext.OPENID;
  let res = generateDefaultRes();
  
  try {
    // 查询符合条件的优惠券包
    const [couponPackagesRes, couponRes] = await Promise.all([
      db.collection("coupon_config").where({available_address: _.in([schoolAddressCode])}).get(),
      db.collection('coupon_record').where({ out_user_id: openId_ }).orderBy("create_ts", "desc").limit(100).get(),
    ]);
    
    const couponDocs = couponRes.data;
    // 最新的券包
    const schoolCouponPackageConfigDoc = couponPackagesRes.data.length > 0
        ? couponPackagesRes.data.reduce((max, current) =>
            current.coupon_package_version > max.coupon_package_version ? current : max
        ) : null;
    
    if (schoolCouponPackageConfigDoc) {
      const couponsHasClaimed = couponsFromCurVersionPackageConfig(couponDocs, schoolCouponPackageConfigDoc);
      const schoolCouponPackageVo = buildCouponPackageVo(schoolCouponPackageConfigDoc);
      if (couponsHasClaimed.length > 0) {
        const schoolCouponPackageClaimedVo = {
          ...schoolCouponPackageVo,
          hasClaimed: true,
        }
        res.data = schoolCouponPackageClaimedVo;
      } else {
        const schoolCouponPackageToClaimVo = {
          ...schoolCouponPackageVo,
          hasClaimed: false,
        }
        res.data = schoolCouponPackageToClaimVo;
      }
    } else {
      res.data = null;
    }

    return res;
  } catch (error) {
    console.error("Error:", error.stack || error);
    return {
      code: 500,
      message: "Error processing request",
      error: error.stack || error.message
    };
  }
}

module.exports = {
  claimCoupon: claimCoupon,
  getCouponsByUserId: getCouponsByUserId,
  showCouponsBySchool: showCouponsBySchool
};
